<?php

class DateTimes
{
	public static function getTimeByFormat($format, $time = null)
	{
		if (is_string($time))
			$time = strtotime($time);
		
		return strtotime(date($format, $time ? $time : time()));
	}
	
	public static function getHourTime($time = null)
	{
		return self::getTimeByFormat('Y-m-d H:00:00', $time);
	}
	
	public static function getDayTime($time = null)
	{
		return self::getTimeByFormat('Y-m-d 00:00:00', $time);
	}
	
	public static function getMonthTime($time = null)
	{
		return self::getTimeByFormat('Y-m-01 00:00:00', $time);
	}
	
	public static function getYearTime($time = null)
	{
		return self::getTimeByFormat('Y-01-01 00:00:00', $time);
	}
	
	/******************** week methods ********************/
	public static function getWeekNum($year = null)
	{
		$year		= $year ? intval($year) : date('Y');
		$lastWeek	= date('W', strtotime($year.'-12-31'));
		
		if ($lastWeek == 1)
			$lastWeek = date('W', strtotime($year.'-12-24'));
		
		return $lastWeek;
	}
	
	public static function getWeekFirstDay($week = 1, $year = null)
	{
		$week			= intval($week);
		$year			= $year ? intval($year) : date('Y');
		$firstDay		= $year.'-01-01';
		$firstDayTime	= strtotime($firstDay);
		$firstWeek		= date('W', $firstDayTime);
		$weekDay		= date('w', $firstDayTime);
		
		if ($firstWeek == 1)
		{
			if ($weekDay != 1)
				$firstDay = ($year - 1).'-12-'.(32 - ($weekDay ? $weekDay - 1 : 6));
		}
		else $firstDay = $year.'-01-0'.(1 + ($weekDay ? 8 - $weekDay : 1));
		
		return $week > 1 ? date('Y-m-d', strtotime($firstDay) + 3600 * 24 * 7 * ($week - 1)) : $firstDay;
	}
	
	public static function getWeekDays($week = 1, $year = null)
	{
		$firstDay	= self::getWeekFirstDay($week, $year);
		$lastDay	= date('Y-m-d', strtotime('+6 days', strtotime($firstDay)));
		
		return array($firstDay, $lastDay);
	}
	
	public static function getAllWeekDays($year = null)
	{
		$year		= $year ? intval($year) : date('Y');
		$weekNum	= self::getWeekNum($year);
		$weekDays	= array();
		
		for ($i = 1; $i <= $weekNum; $i++)
			$weekDays[$i] = self::getWeekDays($i, $year);
		
		return $weekDays;
	}
}
